package com.example.italkapp2.controller.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.italkapp2.R;
import com.example.italkapp2.controller.activity.AddContactActivity;
import com.example.italkapp2.controller.activity.ChatActivity;
import com.example.italkapp2.controller.activity.GroupListActivity;
import com.example.italkapp2.controller.activity.InviteActivity;
import com.example.italkapp2.controller.adapter.ContactAdapter;
import com.example.italkapp2.model.Model;
import com.example.italkapp2.model.bean.UserInfo;
import com.example.italkapp2.model.dao.ContactTableDao;
import com.example.italkapp2.model.db.DBManager;
import com.example.italkapp2.utils.Constant;
import com.example.italkapp2.utils.SpUtils;
import com.example.italkapp2.utils.myParse;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.interfaces.OnItemClickListener;
import com.hyphenate.easeui.modules.contact.EaseContactLayout;
import com.hyphenate.easeui.modules.contact.EaseContactListFragment;
import com.hyphenate.easeui.modules.contact.EaseContactListLayout;
import com.hyphenate.easeui.modules.contact.model.EaseContactCustomBean;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.widget.EaseTitleBar;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.ContentValues.TAG;

//联系人列表页面
public class ContactListFragment extends Fragment {

    private String mHxid;
    private ListView lv_contact;
    private Button btn_contact_list_search;
    private ImageView iv_invitation_notif;
    private LocalBroadcastManager mLBM;
    private LinearLayout ll_contact_invitation;
    private LinearLayout ll_group_item;
    private ContactAdapter contactAdapter;
    private BroadcastReceiver ContactListChangerReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //只要广播接收方的邀请信息有变化就刷新页面
            getContactFromHxServer();
        }
    };
    private BroadcastReceiver ContactInviteChangerReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //更新红点显示
            iv_invitation_notif.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);
        }
    };
    private BroadcastReceiver GroupChangeReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //更新红点显示
            iv_invitation_notif.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,true);
        }
    };
    private ContactAdapter.OnContactListener mOnContactListener=new ContactAdapter.OnContactListener() {
        //点击该联系人条目进入消息页面
        @Override
        public void onLinerLayoutClick(UserInfo userInfo) {
            Intent intent = new Intent(getActivity(), ChatActivity.class);
            startActivity(intent);
        }
    };



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=View.inflate(getActivity(),R.layout.fragment_contact_list,null);

        intiView(view);
        intiData();

        return view;
    }

    private void intiView(View view){
        /*//获取加号按钮点击事件
        tb_contract_title=view.findViewById(R.id.tb_contract_title);
        //按钮点击事件处理
        tb_contract_title.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddContactActivity.class);
                startActivity(intent);
            }
        });*/

        //获取邀请信息条目的点击对象
        ll_contact_invitation=view.findViewById(R.id.ll_contact_invitation);
        //条目点击事件处理
        ll_contact_invitation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //红点处理
                iv_invitation_notif.setVisibility(View.GONE);
                SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE,false);

                //邀请信息列表页面
                Intent intent = new Intent(getActivity(), InviteActivity.class);
                startActivity(intent);
            }
        });

        //获取群组条目的点击对象
        ll_group_item=view.findViewById(R.id.ll_group_item);
        //条目点击事件处理
        ll_group_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GroupListActivity.class);
                startActivity(intent);
            }
        });


        //获取联系人控件
        lv_contact=view.findViewById(R.id.lv_contact);


        //获取红点对象
        iv_invitation_notif=view.findViewById(R.id.iv_invitation_notif);
        Boolean isNewInvite = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE, false);
        iv_invitation_notif.setVisibility(isNewInvite?View.VISIBLE:View.GONE);

        //搜索按钮点击事件
        btn_contact_list_search = view.findViewById(R.id.btn_contact_list_search);
        btn_contact_list_search.setOnClickListener(v -> Log.e(TAG, "intiView: btn_contact_list_search"));

        //从环信服务器获取所有的联系人信息
        getContactFromHxServer();
    }

    private void intiData() {
        contactAdapter=new ContactAdapter(getActivity(),mOnContactListener);
        lv_contact.setAdapter(contactAdapter);

        //刷新方法
        refreshContact();

        //注册广播
        mLBM = LocalBroadcastManager.getInstance(getActivity());

        //全局广播接收者,负责接收邀请改变的广播事件
        mLBM.registerReceiver(ContactInviteChangerReceiver,new IntentFilter(Constant.CONTACT_INVITE_CHANGED));
        //全局广播接收者，负责接收联系人信息变化的广播
        mLBM.registerReceiver(ContactListChangerReceiver,new IntentFilter(Constant.CONTACT_CHANGED));
        //全局广播接收者，负责接收群信息变化的广播
        mLBM.registerReceiver(GroupChangeReceiver,new IntentFilter(Constant.GROUP_INVITE_CHANGED));

        // 从环信服务器获取所有的联系人信息
        getContactFromHxServer();

        //注册一下listView和contextMenu
        registerForContextMenu(lv_contact);
    }

    //初始化页面菜单
    @Override
    public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        //获取hxid
        int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
        UserInfo userInfo =  (UserInfo) lv_contact.getItemAtPosition(position);
        mHxid=userInfo.getHxid();

        //添加布局
        getActivity().getMenuInflater().inflate(R.menu.delete,menu);
    }

    //页面菜单选择器
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {

        if(item.getItemId()==R.id.contact_delete){
            //执行删除选中的联系人操作
            deleteContact();
            return true;
        }
        return super.onContextItemSelected(item);
    }

    //执行删除选中的联系人操作
    private void deleteContact() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //从环信服务器中删除联系人
                    EMClient.getInstance().contactManager().deleteContact(mHxid);

                    //本地数据库的更新
                    Model.getInstance().getDbManager().getContactTableDao().deleteContactByHxId(mHxid);

                    if(getActivity()==null){
                        return;
                    }

                    //刷新页面
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //弹出提示
                            Toast.makeText(getActivity(),"删除"+mHxid+"成功",Toast.LENGTH_SHORT).show();
                            //刷新页面
                            refreshContact();
                        }
                    });


                } catch (HyphenateException e) {
                    e.printStackTrace();
                    if(getActivity()==null){
                        return;
                    }
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //弹出提示
                            Toast.makeText(getActivity(),"删除"+mHxid+"失败",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    //从环信服务器获取所有的联系人信息
    private void getContactFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取到所有好友的环信id
                    List<String> hxids = EMClient.getInstance().contactManager().getAllContactsFromServer();

                    //校验
                    if(hxids!=null &&hxids.size()>=0){
                        List<UserInfo> contacts = new ArrayList<>();
                        String url;
                        for(String hxid:hxids){
                            UserInfo userInfo = new UserInfo(hxid);
                            if (hxid.charAt(0) < '0' || hxid.charAt(0) > '9') {
                                url = "https://picsum.photos/id/" +
                                        myParse.getInstance().paraseIntInRange(hxid, 1000) + "/200";
                            } else {
                                url = "https://picsum.photos/id/" + hxid + "/200";
                            }
                            userInfo.setPhoto(url);
                            contacts.add(userInfo);
                        }

                        //保存好友信息到本地数据库
                        Model.getInstance().getDbManager().getContactTableDao().saveContacts(contacts,true);

                        //刷新fragment有风险,切换到会话页面的时候联系人页面有可能为空（比如切换到设置页面或者消息页面的时候）
                        if(getActivity()==null){return;}

                        //刷新页面
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //刷新页面的方法
                                refreshContact();
                            }
                        });
                    }
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void refreshContact() {

        Model instance = Model.getInstance();
        DBManager dbManager = instance.getDbManager();
        ContactTableDao contactTableDao = dbManager.getContactTableDao();
        List<UserInfo> contacts = contactTableDao.getContacts();

        //获取数据
//        List<UserInfo> contacts = Model.getInstance().getDbManager().getContactTableDao().getContacts();

        //校验
        if (contacts!=null && contacts.size()>=0){
            //设置数据
            Map<String,EaseUser> contactsMap=new HashMap<>();
            //转换,封装easeUser到map中
            for(UserInfo contact:contacts){
                EaseUser easeUser=new EaseUser(contact.getHxid());
                contactsMap.put(contact.getHxid(),easeUser);
            }


            //因为easeUI的方法有误，所以不在此写，在下面另手写一个加载联系人列表的方法
            //得到联系人的集合
            //setContactsMap(contactsMap);
            //刷新页面
            //refresh();

            //刷新适配器
            contactAdapter.refresh(contacts);
        }
    }



    @Override
    public void onDestroy() {
        super.onDestroy();

        //关闭广播
        mLBM.unregisterReceiver(ContactInviteChangerReceiver);
        mLBM.unregisterReceiver(ContactListChangerReceiver);
        mLBM.unregisterReceiver(GroupChangeReceiver);
    }
}